#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
#include <cstdio>
#include <ctime>
#include <mutex>
#include <cstdlib>



class Ticket
{
private:
    int tickets;


public:
    Ticket()
    :tickets(1000)
    {}

    bool GetTicket()
    {
        static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
        bool res = true;
        pthread_mutex_lock(&mtx);
        pthread_mutex_lock(&mtx);
        if(tickets > 0)
        {
            usleep(1000);
            std::cout << "我是[" << pthread_self() << "]我要抢的票是：" << tickets << std::endl;
            tickets--;
            printf("");

        }
        else
        {
            printf("票已经被抢空了\n");
            res = false;
        }
        pthread_mutex_unlock(&mtx);
        return res;
    }
    ~Ticket()
    {

    }
};

// void *ThreadRun(void *args)
// {
//     std::string tname = (char*)args;
//     while(true)
//     {
//         std::cout<<tname<<"is running..." << std::endl;
//         sleep(1);
//     }
// }

void *ThreadRoutine(void *args)
{
    Ticket *t = (Ticket*)args;
    while(true)
    {
        if(!t->GetTicket())
        {
            break;
        }
    }
}

int main()
{
    Ticket *t = new Ticket();
    pthread_t tid[5];
    for(int i = 0; i < 5; i++)
    {
        int *id = new int(i);
        pthread_create(tid+i, nullptr, ThreadRoutine, (void*)t);
    }
    for(int i = 0; i < 5; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    return 0;
}